﻿using Nop.Admin.Models.Common;
using Nop.Admin.Models.XJ;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.XJ;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.XJ;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Mvc;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
	public class EquipmentStockInController : BaseAdminController
	{
		#region Fields
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IOrganizationService _organizationServce;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJEquipmentStockLogService _xJEquipmentStockLogService;
		private readonly IXJEquipmentStockInService _xJEquipmentStockInService;
		private readonly IXJEquipmentStockInDetailService _xJEquipmentStockInDetailService;
		private readonly IXJEquipmentStockOutService _xJEquipmentStockOutService;
		private readonly IXJEquipmentStockOutDetailService _xJEquipmentStockOutDetailService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJEquipmentStockInService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public EquipmentStockInController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IOrganizationService organizationServce,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJEquipmentStockLogService xJEquipmentStockLogService,
			IXJEquipmentStockInService xJEquipmentStockInService,
			IXJEquipmentStockInDetailService xJEquipmentStockInDetailService,
			IXJEquipmentStockOutService xJEquipmentStockOutService,
			IXJEquipmentStockOutDetailService xJEquipmentStockOutDetailService,
			IXJInspectionService xJInspectionService,
			IXJEquipmentStockInService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			ICustomerActivityService customerActivityService,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._organizationServce = organizationServce;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJEquipmentStockLogService = xJEquipmentStockLogService;
			this._xJEquipmentStockInService = xJEquipmentStockInService;
			this._xJEquipmentStockInDetailService = xJEquipmentStockInDetailService;
			this._xJEquipmentStockOutService = xJEquipmentStockOutService;
			this._xJEquipmentStockOutDetailService = xJEquipmentStockOutDetailService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._customerActivityService = customerActivityService;
			this._logger = logger;
		}
		#endregion

		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var model = new EquipmentStockInListModel();
			model.AvailableStates.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			Type enumInspectionType = typeof(StockInStateEnum);
			Enum.GetNames(enumInspectionType).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumInspectionType, Enum.Parse(enumInspectionType, s), "d");
				model.AvailableStates.Add(new SelectListItem { Text = s, Value = value });
			});
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult List(DataSourceRequest command, EquipmentStockInListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedKendoGridJson();

			var customer = _workContext.CurrentCustomer;
			if (customer.IsAdmin() || customer.IsKeyLeader() || customer.IsResponsibleLeader() || customer.IsWarehouseKeeper())
			{
				var ins = _xJEquipmentStockInService.GetAllStockIns(
				sNo: model.SearchSNo,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var gridModel = new DataSourceResult
				{
					Data = ins.Select(x =>
					{
						var categoryModel = new EquipmentStockInModel
						{
							Id = x.Id,
							SNo = x.SNo,
							CustomerId = x.CustomerId,
							CreatedOn = x.CreatedOn,
							State = x.State,
							StateName = Enum.GetName(typeof(StockInStateEnum), x.State)
						};
						return categoryModel;
					}),
					Total = ins.TotalCount
				};
				return Json(gridModel);
			}
			else if (customer.IsDepartmentManager() && customer.DepartmentId > 0)
			{
				var ins = _xJEquipmentStockInService.GetAllStockIns(
				sNo: model.SearchSNo,
				departmentId: customer.DepartmentId,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var gridModel = new DataSourceResult
				{
					Data = ins.Select(x =>
					{
						var categoryModel = new EquipmentStockInModel
						{
							Id = x.Id,
							SNo = x.SNo,
							CustomerId = x.CustomerId,
							CreatedOn = x.CreatedOn,
							State = x.State,
							StateName = Enum.GetName(typeof(StockInStateEnum), x.State)
						};
						return categoryModel;
					}),
					Total = ins.TotalCount
				};
				return Json(gridModel);
			}
			else
			{
				var ins = _xJEquipmentStockInService.GetAllStockIns(
				sNo: model.SearchSNo,
				customerId: customer.Id,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var gridModel = new DataSourceResult
				{
					Data = ins.Select(x =>
					{
						var categoryModel = new EquipmentStockInModel
						{
							Id = x.Id,
							SNo = x.SNo,
							CustomerId = x.CustomerId,
							CreatedOn = x.CreatedOn,
							State = x.State,
							StateName = Enum.GetName(typeof(StockInStateEnum), x.State)
						};
						return categoryModel;
					}),
					Total = ins.TotalCount
				};
				return Json(gridModel);
			}
		}
		#endregion

		#region Create / Edit / Delete

		public virtual ActionResult Create()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();
			var customer = _workContext.CurrentCustomer;
			if (null != customer)
			{
				var stockIn = _xJEquipmentStockInService.GetStockInByCustomerId(customer.Id);
				if (null != stockIn && !stockIn.Deleted)
				{
					return RedirectToAction("Edit", new { id = stockIn.Id });
				}
				else
				{
					stockIn = new XJEquipmentStockIn
					{
						SNo = _xJEquipmentStockInService.GenerateNo(),
						State = (int)StockInStateEnum.保存,
						CustomerId = customer.Id,
						CustomerName = customer.TrueName,
						DepartmentId = customer.DepartmentId,
						DepartmentName = customer.DepartmentName,
						CreatedOn = DateTime.Now,
					};
					_xJEquipmentStockInService.InsertXJEquipmentStockIn(stockIn);
					_customerActivityService.InsertActivity("AddNewEquipmentStockIn", "新增入库记录：{0}", stockIn.Id);
					return RedirectToAction("Edit", new { id = stockIn.Id });
				}
			}

			var model = new EquipmentStockInModel
			{
				SNo = _xJEquipmentStockInService.GenerateNo(),
				CustomerId = customer.Id,
				CustomerName = customer.TrueName,
				DepartmentName = customer.DepartmentName,
				CreatedOn = DateTime.Now,
			};

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Create(EquipmentStockInModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;
			if (ModelState.IsValid)
			{
				if (!continueEditing)
				{
					if (model.Id == 0 || !_xJEquipmentStockInDetailService.GetAllStockInDetails(inId: model.Id).Any())
					{
						ErrorNotification("不能提交");
						return View(model);
					}
				}
				int state = (int)StockInStateEnum.保存;
				// 默认由部门领导审核，没有部门的直接仓管确认入库
				if (!continueEditing)
					state = customer.DepartmentId == 0 ? (int)StockInStateEnum.待入库 : (int)StockInStateEnum.待审核;
				var stockIn = new XJEquipmentStockIn
				{
					SNo = _xJEquipmentStockInService.GenerateNo(),
					State = state,
					CustomerId = customer.Id,
					CustomerName = customer.TrueName,
					DepartmentId = customer.DepartmentId,
					DepartmentName = customer.DepartmentName,
					CreatedOn = DateTime.Now,
				};
				_xJEquipmentStockInService.InsertXJEquipmentStockIn(stockIn);

				//activity log
				_customerActivityService.InsertActivity("AddNewEquipmentStockIn", "新增入库记录：{0}", stockIn.SNo);

				SuccessNotification("保存成功");

				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = stockIn.Id });
				}
				return RedirectToAction("List");
			}

			return View(model);
		}

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");
			if (stockIn.State > (int)StockInStateEnum.待审核)
			{
				ErrorNotification("不能编辑");
				return RedirectToAction("List");
			}

			var customer = _workContext.CurrentCustomer;
			if (customer.Id != stockIn.CustomerId)
				return RedirectToAction("List");

			var model = new EquipmentStockInModel
			{
				Id = stockIn.Id,
				SNo = stockIn.SNo,
				State = stockIn.State,
				CustomerId = stockIn.CustomerId,
				CustomerName = stockIn.CustomerName,
				DepartmentName = stockIn.DepartmentName,
				CreatedOn = stockIn.CreatedOn,
			};

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(EquipmentStockInModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(model.Id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");
			if (stockIn.State > (int)StockInStateEnum.待审核)
			{
				ErrorNotification("不能编辑");
				return View(model);
			}

			if (ModelState.IsValid)
			{
				var customer = _workContext.CurrentCustomer;
				if (!continueEditing && !_xJEquipmentStockInDetailService.GetAllStockInDetails(inId: model.Id).Any())
				{
					ErrorNotification("不能提交");
					return View(model);
				}
				int state = (int)StockInStateEnum.保存;
				// 默认由部门领导审核，没有部门的直接仓管确认入库
				if (!continueEditing)
					state = customer.DepartmentId == 0 ? (int)StockInStateEnum.待入库 : (int)StockInStateEnum.待审核;
				stockIn.State = state;
				_xJEquipmentStockInService.UpdateXJEquipmentStockIn(stockIn);

				//activity log
				_customerActivityService.InsertActivity("EditStockIn", "编辑入库记录：{0}", stockIn.Id);

				SuccessNotification("保存成功");
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = stockIn.Id });
				}
				return RedirectToAction("List");
			}

			return View(model);
		}

		public virtual ActionResult View(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new EquipmentStockInModel
			{
				Id = stockIn.Id,
				SNo = stockIn.SNo,
				Reviewer = stockIn.Reviewer,
				ReviewOn = stockIn.ReviewOn,
				Keeper = stockIn.Keeper,
				KeeperOn = stockIn.KeeperOn,
				State = stockIn.State,
				CustomerId = stockIn.CustomerId,
				CustomerName = stockIn.CustomerName,
				DepartmentName = stockIn.DepartmentName,
				CreatedOn = stockIn.CreatedOn,
			};
			return View(model);
		}

		public virtual ActionResult Audit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new EquipmentStockInModel
			{
				Id = stockIn.Id,
				SNo = stockIn.SNo,
				State = stockIn.State,
				Reviewer = stockIn.Reviewer,
				ReviewOn = stockIn.ReviewOn,
				Keeper = stockIn.Keeper,
				KeeperOn = stockIn.KeeperOn,
				CustomerId = stockIn.CustomerId,
				CustomerName = stockIn.CustomerName,
				DepartmentName = stockIn.DepartmentName,
				CreatedOn = stockIn.CreatedOn,
			};
			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-pass", "pass")]
		public virtual ActionResult Audit(EquipmentStockInModel model, bool pass)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(model.Id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");
			if (stockIn.State != (int)StockInStateEnum.待审核)
			{
				ErrorNotification("无需审核");
				return View(model);
			}
			var customer = _workContext.CurrentCustomer;
			if (!customer.IsAdmin() && !(customer.IsDepartmentManager() && customer.DepartmentId == stockIn.DepartmentId))
			{
				ErrorNotification("不能审核");
				return View(model);
			}

			stockIn.Reviewer = customer.TrueName;
			stockIn.ReviewOn = DateTime.Now;
			stockIn.State = pass ? (int)StockInStateEnum.待入库 : (int)StockInStateEnum.驳回;
			_xJEquipmentStockInService.UpdateXJEquipmentStockIn(stockIn);
			//activity log
			_customerActivityService.InsertActivity("AuditStockOut", "审核入库记录：{0}", stockIn.Id);

			SuccessNotification("操作成功");
			return RedirectToAction("List");
		}

		public virtual ActionResult In(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(id);
			if (stockIn == null || stockIn.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new EquipmentStockInModel
			{
				Id = stockIn.Id,
				SNo = stockIn.SNo,
				State = stockIn.State,
				Reviewer = stockIn.Reviewer,
				ReviewOn = stockIn.ReviewOn,
				Keeper = stockIn.Keeper,
				KeeperOn = stockIn.KeeperOn,
				CustomerId = stockIn.CustomerId,
				CustomerName = stockIn.CustomerName,
				DepartmentName = stockIn.DepartmentName,
				CreatedOn = stockIn.CreatedOn,
			};
			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-pass", "pass")]
		public virtual ActionResult In(EquipmentStockInModel model, bool pass)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var customer = _workContext.CurrentCustomer;

			if (ModelState.IsValid)
			{
				var result = _xJEquipmentStockInService.In(model.Id, pass, customer);
				if (!result.Result)
				{
					ErrorNotification(result.Msg ?? "不能入库");
					return View(model);
				}
				//activity log
				_customerActivityService.InsertActivity("ConfirmStockOut", "确认入库记录：{0}", model.Id);

				SuccessNotification("操作成功");
				return RedirectToAction("List");
			}

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(id);
			if (stockIn == null)
				//No equipment found with the specified id
				return RedirectToAction("List");

			_xJEquipmentStockInService.DeleteXJEquipmentStockIn(stockIn);

			//activity log
			_customerActivityService.InsertActivity("DeleteStockIn", "删除入库记录：{0}", stockIn.Id);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}

		#endregion

		#region Detail

		[HttpPost]
		public virtual ActionResult DetailList(DataSourceRequest command, EquipmentStockInListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedKendoGridJson();

			var customer = _workContext.CurrentCustomer;

			if (customer.IsAdmin() || customer.IsKeyLeader() || customer.IsResponsibleLeader() || customer.IsWarehouseKeeper())
			{
				var outs = _xJEquipmentStockInDetailService.GetEquipmentStockInDetails(
				equipmentId: model.SearchEquipmentId,
				departmentId: model.SearchDepartmentId,
				customerId: model.SearchUserId,
				sno: model.SearchSNo,
				name: model.SearchName,
				startOn: model.SearchStartOn,
				endOn: model.SearchEndOn,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var total = _xJEquipmentStockInDetailService.GetTotal(
					equipmentId: model.SearchEquipmentId,
					departmentId: model.SearchDepartmentId,
					customerId: model.SearchUserId,
					sno: model.SearchSNo,
					name: model.SearchName,
					startOn: model.SearchStartOn,
					endOn: model.SearchEndOn,
					state: model.SearchState
					);
				var gridModel = new DataSourceResult
				{
					ExtraData = total,
					Data = outs.Select(x =>
					{
						x.StateName = Enum.GetName(typeof(StockInStateEnum), x.State);
						x.Total = x.Amount * x.Price;
						return x;
					}),
					Total = outs.TotalCount
				};
				return Json(gridModel);
			}
			else if (customer.IsDepartmentManager() && customer.DepartmentId > 0)
			{
				var outs = _xJEquipmentStockInDetailService.GetEquipmentStockInDetails(
				equipmentId: model.SearchEquipmentId,
				departmentId: customer.DepartmentId,
				customerId: model.SearchUserId,
				sno: model.SearchSNo,
				name: model.SearchName,
				startOn: model.SearchStartOn,
				endOn: model.SearchEndOn,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var total = _xJEquipmentStockInDetailService.GetTotal(
					equipmentId: model.SearchEquipmentId,
				departmentId: customer.DepartmentId,
					customerId: model.SearchUserId,
					sno: model.SearchSNo,
					name: model.SearchName,
					startOn: model.SearchStartOn,
					endOn: model.SearchEndOn,
					state: model.SearchState
					);
				var gridModel = new DataSourceResult
				{
					ExtraData = total,
					Data = outs.Select(x =>
					{
						x.StateName = Enum.GetName(typeof(StockInStateEnum), x.State);
						x.Total = x.Amount * x.Price;
						return x;
					}),
					Total = outs.TotalCount
				};
				return Json(gridModel);
			}
			else
			{
				var outs = _xJEquipmentStockInDetailService.GetEquipmentStockInDetails(
				equipmentId: model.SearchEquipmentId,
				customerId: customer.Id,
				sno: model.SearchSNo,
				name: model.SearchName,
				startOn: model.SearchStartOn,
				endOn: model.SearchEndOn,
				state: model.SearchState,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
				var total = _xJEquipmentStockInDetailService.GetTotal(
					equipmentId: model.SearchEquipmentId,
					customerId: customer.Id,
					sno: model.SearchSNo,
					name: model.SearchName,
					startOn: model.SearchStartOn,
					endOn: model.SearchEndOn,
					state: model.SearchState
					);
				var gridModel = new DataSourceResult
				{
					ExtraData = total,
					Data = outs.Select(x =>
					{
						x.StateName = Enum.GetName(typeof(StockInStateEnum), x.State);
						x.Total = x.Amount * x.Price;
						return x;
					}),
					Total = outs.TotalCount
				};
				return Json(gridModel);
			}
		}

		[HttpPost]
		public virtual ActionResult Details(DataSourceRequest command, int inId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedKendoGridJson();

			var stockInDetails = _xJEquipmentStockInDetailService.GetAllStockInDetails(inId: inId);

			var gridModel = new DataSourceResult
			{
				Data = stockInDetails.Select(x =>
				{
					var categoryModel = new EquipmentStockInDetailModel
					{
						Id = x.Id,
						EquipmentStockInId = x.EquipmentStockInId,
						EquipmentId = x.EquipmentId,
						Name = x.Name,
						Manufacturer = x.Manufacturer,
						Specification = x.Specification,
						Price = x.Price,
						Amount = x.Amount,
					};
					return categoryModel;
				}),
				Total = stockInDetails.Count(),
			};

			return Json(gridModel);
		}

		public virtual ActionResult DetailUpdate(EquipmentStockInDetailModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var detail = _xJEquipmentStockInDetailService.GetXJEquipmentStockInDetailById(model.Id) ?? throw new ArgumentException("No stockin detail mapping found with the specified id");
			detail.Name = model.Name;
			detail.Manufacturer = model.Manufacturer;
			detail.Specification = model.Specification;
			detail.Price = model.Price;
			detail.Amount = model.Amount;
			_xJEquipmentStockInDetailService.UpdateXJEquipmentStockInDetail(detail);

			return new NullJsonResult();
		}

		/// <summary>
		/// 配件列表
		/// </summary>
		/// <param name="command"></param>
		/// <param name="planId"></param>
		/// <returns></returns>
		[HttpPost]
		public virtual ActionResult EquipmentList(DataSourceRequest command, EquipmentListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedKendoGridJson();
			//int[] equipmentIds = _xJEquipmentStockInDetailService.GetEquipmentIds(model.StockInId);

			var categories = _xJEquipmentService.GetAllEquipments4StockIn(
				stockInId: model.StockInId,
				categoryId: model.SearchCategoryId,
				placeId: model.SearchPlaceId,
				name: model.SearchName,
				pp: model.SearchManufacturer,
				gg: model.SearchSpecification,
				onlyStock: model.OnlyStock,
				onlyWarn: model.OnlyWarn,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					x.Breadcrumb = x.GetFormattedBreadCrumb(_xJEquipmentService);
					return x;
				}),
				Total = categories.TotalCount
			};

			return Json(gridModel);
		}

		public virtual ActionResult EquipmentUpdate(XJEquipment4StockIn model, int inId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			if (model.DetailId > 0)
			{
				var detail = _xJEquipmentStockInDetailService.GetXJEquipmentStockInDetailById(model.DetailId);
				if (null != detail)
				{
					detail.Name = model.Name;
					detail.Manufacturer = model.Manufacturer;
					detail.Specification = model.Specification;
					detail.Price = model.Price;
					detail.Amount = model.Amount;
					_xJEquipmentStockInDetailService.UpdateXJEquipmentStockInDetail(detail);
				}
			}
			else
			{
				var detail = _xJEquipmentStockInDetailService.GetXJEquipmentStockInDetailByInIdAndEId(stockInId: inId, equipmentId: model.Id);
				if (null != detail)
				{
					detail.Name = model.Name;
					detail.Manufacturer = model.Manufacturer;
					detail.Specification = model.Specification;
					detail.Price = model.Price;
					detail.Amount = model.Amount;
					_xJEquipmentStockInDetailService.UpdateXJEquipmentStockInDetail(detail);
				}
				else
				{
					detail = new XJEquipmentStockInDetail
					{
						EquipmentStockInId = inId,
						EquipmentId = model.Id,
						Name = model.Name,
						Manufacturer = model.Manufacturer,
						Specification = model.Specification,
						Price = model.Price,
						Amount = model.Amount,
					};
					_xJEquipmentStockInDetailService.InsertXJEquipmentStockInDetail(detail);
				}
			}

			return new NullJsonResult();
		}

		public virtual ActionResult DetailDelete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var detail = _xJEquipmentStockInDetailService.GetXJEquipmentStockInDetailById(id);
			if (null != detail)
				_xJEquipmentStockInDetailService.DeleteXJEquipmentStockInDetail(detail);

			return new NullJsonResult();
		}

		public virtual ActionResult AccessoryAddPopup(int inId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			var model = new EquipmentListModel
			{
				StockInId = inId
			};

			model.AvailableCategories.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true
			});
			var categorys = _xJEquipmentCategoryService.GetAllCategorys(isConsumables: true, showHidden: false);
			foreach (var c in categorys)
				model.AvailableCategories.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
			return View(model);
		}

		[HttpPost]
		[FormValueRequired("save")]
		public virtual ActionResult AccessoryAddPopup(string btnId, string formId, EquipmentListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageIns))
				return AccessDeniedView();

			if (model.StockInId > 0)
			{
				var stockIn = _xJEquipmentStockInService.GetXJEquipmentStockInById(model.StockInId);
				if (stockIn != null && !stockIn.Deleted && stockIn.State == (int)StockInStateEnum.保存)
				{
					if (model.SelectedProductIds != null)
					{
						var stockInDetails = _xJEquipmentStockInDetailService.GetAllStockInDetails(inId: model.StockInId).ToList();
						foreach (int id in model.SelectedProductIds)
						{
							if (!stockInDetails.Any(m => m.Id == id))
							{
								var equipment = _xJEquipmentService.GetXJEquipmentById(id);
								if (equipment != null)
								{
									_xJEquipmentStockInDetailService.InsertXJEquipmentStockInDetail(new XJEquipmentStockInDetail
									{
										EquipmentStockInId = model.StockInId,
										EquipmentId = equipment.Id,
										Price = equipment.Price,
										//Manufacturer = equipment.Manufacturer,
										//Specification = equipment.Specification,
										//Version = equipment.Version,
										//Technician = equipment.Technician,
										//TechnicianContact = equipment.TechnicianContact,
										Amount = 1
									});
								}
							}
						}
					}
				}
			}

			ViewBag.RefreshPage = true;
			ViewBag.btnId = btnId;
			ViewBag.formId = formId;
			return View(model);
		}

		#endregion
	}
}